package com.xszx.server.service;

import com.xszx.server.dto.Page;
import com.xszx.server.entity.Chapter;
import com.xszx.server.mapper.ChapterMapper;
import com.xszx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    /**
     * 获取全部的大章数据
     * @return
     */
    public Page getAllChapters(Page page){
        int pageNum = page.getPage();
        //将分页计算结果返回给映射器
        page.setPage((page.getPage() - 1)*page.getSize());
        List<Chapter> chapters = chapterMapper.findAll(page);
        page.setList(chapters);//将查询出来的数据封装到page对象中
        page.setTotal(chapterMapper.findCount());
        page.setPage(pageNum);
        return page;
    }
    /**
     * 获取单个大章
     * @return
     */
    public Chapter getChapter(String id){
        return chapterMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取课程下的大章
     * @return
     */
    public List<Chapter> getChaptersByCourse(String courseId){
        return chapterMapper.findChaptersByCourse(courseId);
    }
    /**
     * 删除数据
     * @param id
     * @return
     */
    public int del(String id){
        return chapterMapper.deleteByPrimaryKey(id);
    }

    /**
     * 更新数据
     * @param chapter
     * @return
     */
    public String saveOrUpdate(Chapter chapter){
        if(StringUtils.isEmpty(chapter.getId())){
            chapter.setId(UuidUtil.getShortUuid());
            return (chapterMapper.insert(chapter)>0)?"添加成功":"添加失败";
        }else{
            return (chapterMapper.updateByPrimaryKey(chapter)>0)?"更新成功":"更新失败";
        }
    }
}
